package router

import (
	"context"
	"net/http"
	"rustdesk_api_server/api"
	"rustdesk_api_server/router/middleware"
	"time"

	"github.com/gin-gonic/gin"
)

type Router interface {
	ListenAndServe() error
	Shutdown(ctx context.Context) error
	Initialize() error
	GetEngine() *gin.Engine
}

type router struct {
	Engine *gin.Engine
	Server *http.Server
	addr   string
}

func NewRouter(addr string) Router {
	//gin.SetMode(gin.ReleaseMode)
	gin.DisableConsoleColor()
	r := &router{
		addr: addr,
	}
	r.Initialize()
	return r
}

func (r *router) ListenAndServe() error {
	return r.Server.ListenAndServe()
}

func (r *router) Initialize() error {
	r.Engine = gin.Default()
	r.Engine.Use(gin.Recovery())
	r.Engine.Use(middleware.Gzip())
	r.Engine.Use(middleware.Cors())
	r.Server = &http.Server{
		Addr:           r.addr,
		Handler:        r.Engine,
		MaxHeaderBytes: 1 << 28,
		ReadTimeout:    5 * time.Second,
		WriteTimeout:   5 * time.Second,
	}
	r.Engine.GET("/health", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{"code": 1, "health": "ok"})
	})

	r.InitializeAuthApi()

	return nil
}

func (r *router) GetEngine() *gin.Engine {
	return r.Engine
}

func (r *router) Shutdown(ctx context.Context) error {
	return r.Server.Shutdown(ctx)
}

func (r *router) InitializeAuthApi() {
	authGroup := r.Engine.Group("/api")
	{
		authGroup.POST("/login", api.Api.AuthApi.Login)
		authGroup.POST("/logout", middleware.AuthorizeJWT(), api.Api.AuthApi.Logout)
		authGroup.POST("/ab", middleware.AuthorizeJWT(), api.Api.AddressBookApi.Update)
		authGroup.POST("/ab/get", middleware.AuthorizeJWT(), api.Api.AddressBookApi.Get)
		authGroup.POST("/currentUser", middleware.AuthorizeJWT(), api.Api.UserApi.CurrentUser)
	}
}
